<template>
  <div>
    <a-spin :spinning="spinning">
      <a-divider> {{ $t('example.SIM Settings') }}</a-divider>
      <div class="sim-selection-component">
        <div class="input-group">
          <label class="input-label">{{ $t('example.SIM Select Option') }}</label>
          <a-select v-model="selectedOption" :placeholder="$t('example.Please select an option')" size="large"
            style="width: 100%;">
            <a-select-option v-for="option in options" :key="option.value" :value="option.value">
              {{ option.label }}
            </a-select-option>
          </a-select>
        </div>
        <div class="input-group">
          <label class="input-label">{{ $t('example.Password') }}</label>
          <div class="password-input">
            <a-input :type="showPassword ? 'text' : 'password'" v-model="password" style="width: 100%;" />
            <a-icon :type="showPassword ? 'eye-invisible' : 'eye'" @click="togglePasswordVisibility"
              class="password-toggle" />
          </div>
        </div>
        <a-button type="primary" @click="submitData" class="submit-button">
          {{ $t('example.Submit') }}
        </a-button>
        <!-- <a-input v-model="resp" class="response-input" /> -->
      </div>
    </a-spin>

    <!-- APN 设置 start -->
    <div style="margin-top: 30px;">
      <a-divider> {{ $t('APN.APN Settings') }}</a-divider>
      <a-row style="margin-top: 60px;">
        <a-col :span="24" style="margin-left:14%;">
          <a-form-model :model="form" :rules="rules" ref="form" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item :label="$t('APN.APN List')" prop="selected">
              {{ form.selected.key }}
              <a-select v-model="form.selected" @change="handleChange">
                <a-select-option v-for="(item, index) in APNList " :key="index" :value="item.key">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item :label="$t('APN.APN Name')" prop="apnName">
              <a-input v-model="form.apnName" />
            </a-form-model-item>
            <a-form-model-item :label="$t('APN.APN Username')" prop="username">
              <a-input v-model="form.username" />
            </a-form-model-item>
            <a-form-model-item :label="$t('APN.APN Password')" prop="password">
              <a-input v-model="form.password" />
            </a-form-model-item>
            <a-form-model-item :label="$t('APN.APN authType')" prop="authType">
              <a-input v-model="form.authType" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button type="primary" @click="SaveAPN()" style="float: right;margin-right: 50px;">{{ $t('Save')
                }}</a-button>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>
    </div>
    <!-- APN 设置 end -->
  </div>
</template>

<script>
export default {
  data () {
    // 表单数据项校验
    const notNull = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('APN.not empty')))
      } else {
        callback()
      }
    }

    return {
      resp: '',
      options: [
        { value: 0, label: 'RSIM' },
        { value: 1, label: 'ESIM1' },
        { value: 2, label: 'ESIM2' }
      ],
      selectedOption: null,
      showPassword: false,
      password: '',
      spinning: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 10 },
      form: {
        apnName: '',
        password: '',
        username: '',
        authType: '',
        selected: 0
      },
      APNList: [
        { key: 1, name: '中国联通' },
        { key: 2, name: '中国移动' },
        { key: 3, name: '中国电信' },
        { key: 4, name: '广东电信' }
      ],
      rules: {
        apnName: [{ validator: notNull }],
        password: [{ validator: notNull }],
        authType: [{ validator: notNull }],
        username: [{ validator: notNull }]
      }
    }
  },
  created () {
  },
  mounted () {
    this.$rpc.call('example', 'getSimSelectValue')
      .then(response => {
        this.selectedOption = response.simSelectValue
      })
    this.GetAPN()
  },
  methods: {
    // 持久化SIM卡状态
    applySIMStatus (state) {
      // 新增uci选项
      // const sectionsId = this.$uci.add('oui-httpd', 'sim_status')
      // console.log(sectionsId)
      // this.$uci.set('oui-httpd', sectionsId, 'state', state)
      let sectionsId = ''
      // 读取oui-httpd文件
      this.$uci.load('oui-httpd').then(() => {
        const sections = this.$uci.sections('oui-httpd', 'sim_status') // 获取所有 sim_status sections
        sections.forEach(section => {
          sectionsId = section['.name'] // 赋值 sectionsId
        })
        if (sectionsId === '') {
          return this.$message.error('sectionsId为空, 无法更新UCI')
        }
        this.$uci.set('oui-httpd', sectionsId, 'state', state) // 修改uci值
        // 保存配置
        this.$uci.save().then(() => {
          this.$message.success('配置已保存')
          // 应用配置
          this.$uci.apply().then(() => {
            this.$message.success('配置已应用')
          }).catch(err => {
            this.$message.error('应用配置失败:', err)
          })
        }).catch(err => {
          this.$message.error('保存配置失败:', err)
        })
      })
    },
    // 选择APNList
    handleChange (value) {
      this.form.selected = value
    },
    // 设置APN
    SaveAPN () {
      this.$refs.form.validate(valid => {
        if (!valid) return
        console.log("test")
        // this.$rpc.call('example', 'set_apn').then(res => {
        //   console.log(res)
        // })
      })
    },
    // 获取APN
    GetAPN () {
      // 初始化, 后续需要从后台获取
      // this.form.selected = { key: 2, name: '中国移动' }
      this.form.selected = 2
    },
    togglePasswordVisibility () {
      this.showPassword = !this.showPassword
    },
    // 设置SIM卡
    submitData () {
      if (this.selectedOption !== null && this.password) {
        this.spinning = true
        this.$rpc.call('example', 'setSimSelect', {
          selectedOption: this.selectedOption,
          password: this.password
        }).then(response => {
          // this.resp = response.message
          if (response.message !== 'Success') {
            this.spinning = false
            return this.$message.error('密码错误')
          }
          this.spinning = false
          // uci 保存sim状态
          this.applySIMStatus(this.selectedOption)
          return this.$message.success('设置成功')
        }).catch(err => {
          return this.$message.error(err, 10)
        }).finally(() => {
          this.spinning = false
        })
      } else {
        // alert(this.$t('example.pleaseSelectAndEnterPassword'))
        return this.$message.warning(this.$t('example.pleaseSelectAndEnterPassword'), 10)
      }
    }
  }
}
</script>

<style>
.sim-selection-component {
  width: 500px;
  display: flex;
  flex-direction: column;
  margin: 0 auto;
}

.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.input-label {
  margin-right: 10px;
  white-space: nowrap;
}

.password-input {
  position: relative;
  width: 100%;
}

.password-toggle {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

.submit-button {
  margin: 15px auto;
  width: 15%;
}

.response-input {
  margin-top: 20px;
}
</style>
